package com.zjh.r2dbc.convert;

import com.zjh.r2dbc.entity.Dept;
import com.zjh.r2dbc.entity.Emp;
import com.zjh.r2dbc.entity.EmpVo;
import io.r2dbc.spi.Row;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;

import java.time.LocalDate;

/**
 * @Auther: zjh
 * @Date: 2025/11/5 - 11 - 05 - 8:06
 * @Description: com.zjh.r2dbc
 * @version: 1.0
 */
@ReadingConverter
//这种每次查询Emp都会使用这个转换器 我们可以封装一个Vo用来保护原有的convert ,并且再写一个repositories接口
//public class EmpConvert implements Converter<Row, Emp> {
public class EmpConvert implements Converter<Row, EmpVo> {





        @Override
        public EmpVo convert(Row source) {
            if (source == null) {
                return null;
            }

            // 从 Row 中按列名取出对应字段
            Integer empno = source.get("EMPNO", Integer.class);
            String ename = source.get("ENAME", String.class);
            String job = source.get("JOB", String.class);
            Integer mgr = source.get("MGR", Integer.class);
            LocalDate hiredate = source.get("HIREDATE", LocalDate.class);
            Double sal = source.get("SAL", Double.class);
            Double comm = source.get("COMM", Double.class);
            Integer deptnos = source.get("DEPTNOS", Integer.class);

            // 如果查询语句 JOIN 了 dept 表，则可以尝试取出 dept 信息
            Dept dept = null;
            try {
                // 假设查询语句是 SELECT e.*, d.DNAME, d.LOC FROM emp e LEFT JOIN dept d ...
                String dname = source.get("DNAME", String.class);
                String loc = source.get("LOC", String.class);
                if (dname != null || loc != null) {
                    dept = new Dept(deptnos, dname, loc);
                }
            } catch (Exception ignored) {
                // 如果没有 JOIN dept 表，直接跳过
            }

            // 构造 Emp 对象
            return new EmpVo(empno, ename, job, mgr, hiredate, sal, comm, deptnos, dept);
        }


}
